class AppleStockMonitor {
    constructor() {
        this.isMonitoring = false;
        this.intervalId = null;
        this.nextUpdateTimeout = null;
        this.init();
    }

    init() {
        this.bindEvents();
        this.updateUI();
    }

    bindEvents() {
        document.getElementById('startMonitor').addEventListener('click', () => this.startMonitoring());
        document.getElementById('stopMonitor').addEventListener('click', () => this.stopMonitoring());
        document.getElementById('checkOnce').addEventListener('click', () => this.checkStock());
        document.getElementById('clearLogs').addEventListener('click', () => this.clearLogs());
        
        // 监听产品型号输入变化
        document.getElementById('productModel').addEventListener('input', (e) => {
            if (this.isMonitoring) {
                this.log('产品型号已更改，重新开始监控', 'info');
                this.startMonitoring();
            }
        });
        
        // 监听门店选择变化
        document.getElementById('storeId').addEventListener('change', (e) => {
            if (this.isMonitoring) {
                this.log('门店已更改，重新开始监控', 'info');
                this.startMonitoring();
            }
        });
    }

    async startMonitoring() {
        if (this.isMonitoring) {
            this.stopMonitoring();
        }

        const productModel = document.getElementById('productModel').value.trim();
        if (!productModel) {
            this.showError('请输入产品型号');
            return;
        }

        this.isMonitoring = true;
        this.updateUI();
        this.log('开始监控库存状态', 'info');
        
        // 立即执行一次查询
        await this.checkStock();
        
        // 设置定时器
        this.scheduleNextCheck();
    }

    stopMonitoring() {
        this.isMonitoring = false;
        if (this.intervalId) {
            clearInterval(this.intervalId);
            this.intervalId = null;
        }
        if (this.nextUpdateTimeout) {
            clearTimeout(this.nextUpdateTimeout);
            this.nextUpdateTimeout = null;
        }
        this.updateUI();
        this.log('停止监控', 'info');
    }

    scheduleNextCheck() {
        if (!this.isMonitoring) return;

        const interval = parseInt(document.getElementById('refreshInterval').value) * 1000;
        
        this.nextUpdateTimeout = setTimeout(() => {
            if (this.isMonitoring) {
                this.checkStock().then(() => {
                    this.scheduleNextCheck();
                });
            }
        }, interval);

        this.updateNextUpdateTime(interval);
    }

    updateNextUpdateTime(interval) {
        const nextTime = new Date(Date.now() + interval);
        document.getElementById('nextUpdate').textContent = nextTime.toLocaleTimeString();
    }

    async checkStock() {
        const productModel = document.getElementById('productModel').value.trim();
        const storeId = document.getElementById('storeId').value;

        if (!productModel) {
            this.showError('请输入产品型号');
            return;
        }

        this.showLoading(true);
        this.hideError();

        try {
            const url = `https://www.apple.com.cn/shop/pickup-message-recommendations?fae=true&mts.0=regular&mts.1=compact&searchNearby=true&store=${storeId}&product=${productModel}`;
            
            this.log(`查询库存: ${productModel} @ 门店 ${storeId}`, 'info');
            
            // 由于跨域限制，这里使用代理或者JSONP方式
            // 实际部署时需要配置代理服务器
            const response = await this.fetchWithProxy(url);
            
            if (response.head && response.head.status === "200") {
                this.parseAndDisplayResults(response, productModel);
                this.updateLastUpdateTime();
            } else {
                throw new Error('API返回状态异常');
            }
        } catch (error) {
            this.log(`查询失败: ${error.message}`, 'error');
            this.showError(`查询失败: ${error.message}`);
        } finally {
            this.showLoading(false);
        }
    }

    async fetchWithProxy(url) {
        // 注意：由于浏览器的CORS限制，直接调用Apple API会失败
        // 这里提供几种解决方案的示例代码
        
        try {
            // 方案1: 使用代理服务（需要后端支持）
            const proxyUrl = `/api/proxy?url=${encodeURIComponent(url)}`;
            const response = await fetch(proxyUrl);
            return await response.json();
        } catch (proxyError) {
            // 方案2: 使用公共CORS代理（仅用于测试）
            try {
                const corsProxyUrl = `https://cors-anywhere.herokuapp.com/${url}`;
                const response = await fetch(corsProxyUrl);
                return await response.json();
            } catch (corsError) {
                // 方案3: 模拟数据（用于演示）
                this.log('使用模拟数据进行演示', 'warning');
                return this.getMockData();
            }
        }
    }

    getMockData() {
        // 模拟API返回数据
        return {
            "head": { "status": "200" },
            "body": {
                "PickupMessage": {
                    "stores": [
                        {
                            "storeName": "Apple 王府井",
                            "storeNumber": "R448",
                            "city": "北京",
                            "address": {
                                "address": "Apple 王府井",
                                "address2": "北京市东城区王府井大街138号"
                            },
                            "partsAvailability": {
                                [document.getElementById('productModel').value]: {
                                    "storePickEligible": Math.random() > 0.3,
                                    "pickupSearchQuote": Math.random() > 0.3 ? "今天可取货" : "暂无库存",
                                    "partNumber": document.getElementById('productModel').value,
                                    "pickupDisplay": Math.random() > 0.3 ? "available" : "unavailable",
                                    "pickupType": "店内取货",
                                    "messageTypes": {
                                        "regular": {
                                            "storePickupProductTitle": "iPhone 15 Pro 256GB 深蓝色"
                                        }
                                    },
                                    "buyability": {
                                        "isBuyable": Math.random() > 0.3,
                                        "inventory": Math.floor(Math.random() * 5)
                                    }
                                }
                            }
                        },
                        {
                            "storeName": "Apple 三里屯",
                            "storeNumber": "R463",
                            "city": "北京",
                            "address": {
                                "address": "Apple 三里屯",
                                "address2": "北京市朝阳区三里屯路19号院"
                            },
                            "partsAvailability": {
                                [document.getElementById('productModel').value]: {
                                    "storePickEligible": Math.random() > 0.3,
                                    "pickupSearchQuote": Math.random() > 0.3 ? "今天可取货" : "暂无库存",
                                    "partNumber": document.getElementById('productModel').value,
                                    "pickupDisplay": Math.random() > 0.3 ? "available" : "unavailable",
                                    "pickupType": "店内取货",
                                    "messageTypes": {
                                        "regular": {
                                            "storePickupProductTitle": "iPhone 15 Pro 256GB 深蓝色"
                                        }
                                    },
                                    "buyability": {
                                        "isBuyable": Math.random() > 0.3,
                                        "inventory": Math.floor(Math.random() * 5)
                                    }
                                }
                            }
                        }
                    ]
                }
            }
        };
    }

    parseAndDisplayResults(data, productModel) {
        const resultsContainer = document.getElementById('stockResults');
        resultsContainer.innerHTML = '';

        if (!data.body || !data.body.PickupMessage || !data.body.PickupMessage.stores) {
            this.showError('未找到门店信息');
            return;
        }

        const stores = data.body.PickupMessage.stores;
        let hasStock = false;

        stores.forEach(store => {
            const storeCard = this.createStoreCard(store, productModel);
            if (storeCard) {
                resultsContainer.appendChild(storeCard);
                
                // 检查是否有库存
                if (store.partsAvailability && store.partsAvailability[productModel]) {
                    const availability = store.partsAvailability[productModel];
                    if (availability.pickupDisplay === 'available' && availability.storePickEligible) {
                        hasStock = true;
                        this.log(`🎉 发现库存! ${store.storeName} - ${availability.pickupSearchQuote}`, 'success');
                        
                        // 播放提示音（如果浏览器支持）
                        this.playNotificationSound();
                        
                        // 发送桌面通知
                        this.sendDesktopNotification(store.storeName, availability.pickupSearchQuote);
                    }
                }
            }
        });

        if (!hasStock) {
            this.log('暂无库存', 'warning');
        }

        if (resultsContainer.children.length === 0) {
            resultsContainer.innerHTML = '<div class="no-results">未找到相关库存信息</div>';
        }
    }

    createStoreCard(store, productModel) {
        if (!store.partsAvailability || !store.partsAvailability[productModel]) {
            return null;
        }

        const availability = store.partsAvailability[productModel];
        const card = document.createElement('div');
        card.className = `store-card ${availability.pickupDisplay}`;

        const statusClass = availability.pickupDisplay === 'available' ? 'available' : 'unavailable';
        const statusText = availability.pickupDisplay === 'available' ? '有库存' : '无库存';
        const statusIcon = availability.pickupDisplay === 'available' ? '✅' : '❌';

        card.innerHTML = `
            <div class="store-header">
                <div>
                    <h3 class="store-name">${store.storeName}</h3>
                    <p class="store-address">${store.address.address2}</p>
                </div>
                <div class="stock-status ${statusClass}">
                    ${statusIcon} ${statusText}
                </div>
            </div>
            <div class="stock-details">
                <div class="detail-item">
                    <span class="detail-label">门店编号:</span>
                    <span class="detail-value">${store.storeNumber}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">产品型号:</span>
                    <span class="detail-value">${availability.partNumber}</span>
                </div>
                ${availability.messageTypes?.regular?.storePickupProductTitle ? 
                    `<div class="detail-item">
                        <span class="detail-label">产品名称:</span>
                        <span class="detail-value">${availability.messageTypes.regular.storePickupProductTitle}</span>
                    </div>` : ''}
                <div class="detail-item">
                    <span class="detail-label">取货状态:</span>
                    <span class="detail-value">${availability.pickupSearchQuote}</span>
                </div>
                ${availability.buyability?.inventory !== undefined ? 
                    `<div class="detail-item">
                        <span class="detail-label">库存数量:</span>
                        <span class="detail-value">${availability.buyability.inventory}</span>
                    </div>` : ''}
            </div>
            ${availability.pickupDisplay === 'available' ? 
                `<div class="action-buttons">
                    <button class="btn btn-primary" onclick="window.open('https://www.apple.com.cn/shop/buy-iphone', '_blank')">
                        立即购买
                    </button>
                </div>` : ''}
        `;

        return card;
    }

    playNotificationSound() {
        try {
            // 创建简单的提示音
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            
            oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
            gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.5);
            
            oscillator.start(audioContext.currentTime);
            oscillator.stop(audioContext.currentTime + 0.5);
        } catch (error) {
            console.log('无法播放提示音:', error);
        }
    }

    sendDesktopNotification(storeName, message) {
        if ('Notification' in window) {
            if (Notification.permission === 'granted') {
                new Notification('🍎 发现iPhone库存!', {
                    body: `${storeName}: ${message}`,
                    icon: 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text y=".9em" font-size="90">🍎</text></svg>'
                });
            } else if (Notification.permission !== 'denied') {
                Notification.requestPermission().then(permission => {
                    if (permission === 'granted') {
                        this.sendDesktopNotification(storeName, message);
                    }
                });
            }
        }
    }

    showLoading(show) {
        const loadingIndicator = document.getElementById('loadingIndicator');
        if (show) {
            loadingIndicator.classList.remove('hidden');
        } else {
            loadingIndicator.classList.add('hidden');
        }
    }

    showError(message) {
        const errorElement = document.getElementById('errorMessage');
        errorElement.textContent = message;
        errorElement.classList.remove('hidden');
    }

    hideError() {
        const errorElement = document.getElementById('errorMessage');
        errorElement.classList.add('hidden');
    }

    updateUI() {
        const startBtn = document.getElementById('startMonitor');
        const stopBtn = document.getElementById('stopMonitor');
        const statusElement = document.getElementById('monitorStatus');

        if (this.isMonitoring) {
            startBtn.disabled = true;
            stopBtn.disabled = false;
            statusElement.textContent = '监控中';
            statusElement.className = 'status running';
        } else {
            startBtn.disabled = false;
            stopBtn.disabled = true;
            statusElement.textContent = '已停止';
            statusElement.className = 'status stopped';
            document.getElementById('nextUpdate').textContent = '-';
        }
    }

    updateLastUpdateTime() {
        const now = new Date();
        document.getElementById('lastUpdate').textContent = now.toLocaleTimeString();
    }

    log(message, level = 'info') {
        const logContainer = document.getElementById('logContainer');
        const logEntry = document.createElement('div');
        logEntry.className = 'log-entry';
        
        const timestamp = new Date().toLocaleTimeString();
        logEntry.innerHTML = `
            <span class="log-timestamp">[${timestamp}]</span>
            <span class="log-level-${level}">${message}</span>
        `;
        
        logContainer.appendChild(logEntry);
        
        // 自动滚动到底部
        if (document.getElementById('autoScroll').checked) {
            logContainer.scrollTop = logContainer.scrollHeight;
        }
        
        // 限制日志条数
        const maxLogs = 100;
        while (logContainer.children.length > maxLogs) {
            logContainer.removeChild(logContainer.firstChild);
        }
    }

    clearLogs() {
        document.getElementById('logContainer').innerHTML = '';
        this.log('日志已清空', 'info');
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.stockMonitor = new AppleStockMonitor();
});